import React, { useState, useEffect, ReactElement } from 'react'
import { Table, Button, Drawer, Form, Input, DatePicker, Space, Tree,message } from 'antd';
import { role, menu, removeRole, getAllMenu, putRole } from '../../apis/role'
import qs, { stringify } from 'querystring'
// 引入
import Drawer1 from "../../component/Drawer1"
import { SettingOutlined, EyeOutlined } from "@ant-design/icons";

// IconFont就是图标组件
export default function index() {
    // const IconFont = createFromIconfontCN({
    //     scriptUrl: "//at.alicdn.com/t/font_2928153_a8ynxy9hpn5.js",
    // });
    const { RangePicker } = DatePicker;
    const onClose = () => {
        setVisible(false);
        // window.location.reload()
    };
    const [visible, setVisible] = useState(false);
    const layout = {
        labelCol: {
            span: 8,
        },
        wrapperCol: {
            span: 16,
        },
    };
    const onFinish = async (values) => {

        let value = {}
        value.roleName = values.roleName1
        value.remark = values.userRemark1
        value.roleId = usreId
        value.menuId = checkedKeys

        const newValue = qs.stringify(value)

        console.log(newValue);

        let res = await putRole(newValue)
        console.log(res);
        if (res.status == 200) {
            message.success("修改成功!")
            setVisible(false);
            allcharge()
        }else{
            message.error("修改失败")
        }

    }
    const validateMessages = {
        // required: '${label} is required!',
        // types: {
        //     email: '${label} is not a valid email!',
        //     number: '${label} is not a valid number!',
        // },
        // number: {
        //     range: '${label} must be between ${min} and ${max}',
        // },
    };

    const [chagrename, setchargename] = useState()
    const [chargeuser, setchargeuser] = useState()
    // const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);
    // const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [roleName1, setRoleName1] = useState("1")
    const [userRemark1, setUserRemark1] = useState("1")
    const [treeData, setTreeData] = useState([])
    const [usreMenu, setUsreMenu] = useState([])
    const [usreId, setUsreId] = useState(null)
    let [usreNewMenu, setUsreNewMenu] = useState([])

    // const onExpand = (expandedKeysValue) => {
    //     console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    //     // or, you can remove all expanded children keys.

    //     setExpandedKeys(expandedKeysValue);
    //     setAutoExpandParent(false);
    // };

    const onCheck = (checkedKeysValue) => {
        //点击获得修改的权限
        console.log('onCheck', checkedKeysValue);
        setCheckedKeys(checkedKeysValue);
        // setUsreNewMenu(checkedKeysValue);
        // console.log("usreNewMenu",checkedKeys);
    };

    const onSelect = (selectedKeysValue, info) => {
        console.log('onSelect', info);
        setSelectedKeys(selectedKeysValue);
    };

    //点击设置
    const showDrawer = async (id) => {
        setUsreId(id)
        let res = await menu(id)
        let res2 = await getAllMenu()
        console.log("res2", res2);
        setTreeData(res2.data.rows.children)
        console.log("treeData", treeData);
        console.log("menu", res);
        setUsreMenu(res.data)
        const userData = data.filter(item => item.roleId == id)
        // console.log(userData);
        setRoleName1(userData[0].roleName)
        setUserRemark1(userData[0].remark)
        setVisible(true);
    };



    const columns = [
        {
            title: '角色',
            dataIndex: 'roleName',
        },
        {
            title: '描述',
            dataIndex: 'remark',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            defaultSortOrder: 'descend',
            sorter: (a, b) => Date.parse(b.createTime) - Date.parse(a.createTime),
        },
        {
            title: '修改时间',
            dataIndex: 'modifyTime',
            defaultSortOrder: 'descend',
            sorter: (a, b) => Date.parse(b.modifyTime) - Date.parse(a.modifyTime),
        },
        {
            title: '操作',
            dataIndex: 'operation',

        },


    ];
    const [selectedRowKeys, setselectedRowKeys] = useState([])
    const [loading, setloading] = useState(false)
    const [chargedata, setchargedata] = useState([])
    const [pageall, setpageall] = useState({
        pageSize: 1000,
        pageNum: 1,
        sortField: "",
        sortOrder: "",
        createTimeFrom: "",
        createTimeTo: "",
        roleName: ""
    })
    const start = () => {
        console.log(1);
        setloading(true);
        setTimeout(() => {
            setselectedRowKeys([])
            setloading(false)
        }, 1000);
    };

    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        setselectedRowKeys(selectedRowKeys)
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const allcharge = async () => {
        const page = qs.stringify(pageall)
        const res = await role(page)
        console.log(res);
        setchargedata(res.data.rows)
    }
    useEffect(() => {
        allcharge()

    }, [])
    const roleName11 = () => {
        console.log(roleName1);

        setRoleName1(roleName1)
    }
    const userRemark11 = () => {
        console.log(userRemark1);

        setUserRemark1(userRemark1)
    }

    const data = [];
    for (let i = 0; i < chargedata.length; i++) {
        if (chargedata[i].licenceImg) {
            chargedata[i].licenceImg = <img src={chargedata[i].licenceImg} alt="" style={{ width: "50px" }} />
        }
        data.push({
            key: i,
            ...chargedata[i],
            operation: (<> <SettingOutlined onClick={() => showDrawer(chargedata[i].roleId)} />

                <EyeOutlined /> </>)
        });
    }
    return (

        <div>
            <div>
                <table style={{ margin: '0 auto' }}>
                    <tbody>
                        <tr>
                            <td>
                                角色:
                            </td>
                            <td>
                                <Input value={chagrename} onChange={(event) => setchargename(event.target.value)}></Input>
                            </td>
                            <td>
                                创建时间:
                            </td>
                            <td>
                                <Input value={chargeuser} onChange={(event) => setchargeuser(event.target.value)}></Input>
                                <Space direction="vertical" size={24}>
                                    <RangePicker placeholder={["开始日期", "结束日期"]} />

                                </Space>,
                            </td>



                        </tr>
                    </tbody>
                </table>
            </div>
            <div style={{ marginBottom: 16 }}>
                <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
                    删除
                </Button>
                <span style={{ marginLeft: 8 }}>
                    {hasSelected ? `选中 ${selectedRowKeys.length} 条` : ''}
                </span>
            </div>
            <div style={{ marginBottom: 5, display: "flex", justifyContent: "space-between" }}>
                <div>
                    <Button style={{ marginRight: "5px" }} onClick={() => add()}>
                        新增
                    </Button>
                    <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
                        删除
                    </Button>
                    <span style={{ marginLeft: 8 }}>
                        {hasSelected ? `选中 ${selectedRowKeys.length} 条` : ''}
                    </span>
                </div>
                <div>
                    <Button style={{ marginRight: "5px" }} onClick={() => modify()}>
                        搜索
                    </Button>
                    <Button onClick={() => clear()}>
                        重置
                    </Button>
                </div>
            </div>
            <Table rowSelection={rowSelection} columns={columns} dataSource={data}
                pagination={
                    {
                        defaultCurrent: 1,
                        defaultPageSize: 5,
                        pageSizeOptions: [5, 10, 15, 20],
                        showSizeChanger: true,
                        showQuickJumper: true
                    }}
            />
            {visible ? <Drawer1
                onClose={onClose}
                visible={visible}
                roleName1={roleName1}
                userRemark1={userRemark1}
                treeData={treeData}
                onFinish={onFinish}
                roleName11={roleName11}
                userRemark11={userRemark11}
                validateMessages={validateMessages}
                layout={layout}
                onCheck={onCheck}
                usreMenu={usreMenu}
                onSelect={onSelect}
            ></Drawer1> : null}

        </div>
    )
}
